package array.sliding_window;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FindAnagrams {

    public List<Integer> findAnagrams(String s, String t) {

        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();
         for (char c : t.toCharArray()) {
             need.put(c, need.getOrDefault(c, 0) + 1);
         }
         int left = 0, right = 0;
         int valid = 0;
         // 记录结果
         List<Integer> res = new ArrayList<>();
         while (right < s.length()) {
             char c = s.charAt(right);
             right++;
             if (need.containsKey(c)) {
                 window.put(c, window.getOrDefault(c, 0) + 1);
                 if (need.get(c).equals(window.get(c)))
                      valid++;
             }

             while (right - left >= t.length()) {
                 // 当窗口符合条件时，将起始索引加入res
                 if (valid == need.size()) {
                     res.add(left);
                 }
                 char d = s.charAt(left);
                 left++;
                 if (need.containsKey(d)) {
                     if (window.get(d).equals(need.get(d)))
                          valid--;
                     window.put(d, window.get(d) - 1);
                 }
             }
         }

         return res;
    }
}
